package cn.donting.plugin.spring.boot.starter;

import cn.donting.plugin.spring.boot.starter.properties.PluginProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * DefaultRequestPlugId
 * @author donting
 *
 */
@Component
public class DefaultRequestPlugId implements RequestPlugId {
    private String[] visit;
    private String visitLKey;

    public DefaultRequestPlugId(PluginProperties plugProperties) {
        visit = plugProperties.getVisit().toUpperCase().split(PluginProperties.separator);
        visitLKey=plugProperties.getVisitLKey();
    }

    @Override
    public String getPlugId(HttpServletRequest request) {
        String[] visit = this.visit;
        for (String key : visit) {
            if (key.equals(PluginProperties.VisitEnum.HEADER.value)) {
                String header = request.getHeader(visitLKey);
                if (header == null) {
                    continue;
                }
                return header;
            }
            if (key.equals(PluginProperties.VisitEnum.URL.value)) {
                String requestURI = request.getRequestURI();
                if (requestURI.length() <= 1) {
                    continue;
                }
                try {
                    String substring = requestURI.substring(1, requestURI.indexOf("/", 1));
                    return substring;
                } catch (Exception e) {
                    return null;
                }
            }
            if (key.equals(PluginProperties.VisitEnum.QUERY.value)) {
                Object attribute = request.getParameter(visitLKey);
                if (attribute != null) {
                    return attribute.toString();
                }
                continue;
            }
        }
        return null;
    }
}
